/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
// Copyright tang.  All rights reserved.
// https://gitee.com/inrgihc/dbswitch
//
// Use of this source code is governed by a BSD-style license
//
// Author: tang (inrgihc@126.com)
// Date : 2020/1/2
// Location: beijing , china
/////////////////////////////////////////////////////////////
package com.je.meta.util.database;

import com.je.common.base.constants.table.TableType;
import com.je.meta.model.database.ColumnDescription;
import com.je.meta.model.database.ColumnMetaData;
import com.je.meta.model.database.TableDescription;
import com.je.meta.model.database.type.ProductTypeEnum;
import com.je.meta.service.dbswitch.common.constant.Const;
import com.je.meta.service.dbswitch.service.AbstractDatabase;
import com.je.meta.service.dbswitch.service.DatabaseFactory;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 拼接SQL工具类
 *
 * @author tang
 */
public final class GenerateSqlUtils {

    public static String getDDLCreateTableSQL(
            ProductTypeEnum type,
            List<ColumnDescription> fieldNames,
            List<String> primaryKeys,
            String schemaName,
            String tableName,
            boolean autoIncr) {
        return getDDLCreateTableSQL(
                DatabaseFactory.getDatabaseInstance(type),
                fieldNames,
                primaryKeys,
                schemaName,
                tableName,
                false,
                null,
                autoIncr);
    }

    public static String getDDLCreateTableSQL(
            AbstractDatabase db,
            List<ColumnDescription> fieldNames,
            List<String> primaryKeys,
            String schemaName,
            String tableName,
            boolean withRemarks,
            String tableRemarks,
            boolean autoIncr) {
        ProductTypeEnum type = db.getDatabaseType();
        StringBuilder sb = new StringBuilder();
        List<String> pks = fieldNames.stream()
                .filter((cd) -> primaryKeys.contains(cd.getFieldName()))
                .map((cd) -> cd.getFieldName())
                .collect(Collectors.toList());

        sb.append(Const.CREATE_TABLE);
        // if(ifNotExist && type!=DatabaseType.ORACLE) {
        // sb.append( Const.IF_NOT_EXISTS );
        // }
        sb.append(db.getQuotedSchemaTableCombination(schemaName, tableName));
        sb.append("(");

        for (int i = 0; i < fieldNames.size(); i++) {
            if (i > 0) {
                sb.append(", ");
            } else {
                sb.append("  ");
            }

            ColumnMetaData v = fieldNames.get(i).getMetaData();
            sb.append(db.getFieldDefinition(v, pks, autoIncr, false, withRemarks));
        }

        if (!pks.isEmpty()) {
            String pk = db.getPrimaryKeyAsString(pks);
            sb.append(", PRIMARY KEY (").append(pk).append(")");
        }

        sb.append(")");
        if (ProductTypeEnum.MYSQL == type) {
            sb.append("ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin");
            if (withRemarks && StringUtils.isNotBlank(tableRemarks)) {
                sb.append(String.format(" COMMENT='%s' ", tableRemarks.replace("'", "\\'")));
            }
        }

        return DDLFormatterUtils.format(sb.toString());
    }

    public static List<String> getDDLCreateTableSQL(
            ProductTypeEnum type,
            List<ColumnDescription> fieldNames,
            List<String> primaryKeys,
            String schemaName,
            String tableName,
            String tableRemarks,
            boolean autoIncr) {
        AbstractDatabase db = DatabaseFactory.getDatabaseInstance(type);
        String createTableSql = getDDLCreateTableSQL(db, fieldNames, primaryKeys, schemaName,
                tableName, true, tableRemarks, autoIncr);
        if (type.noCommentStatement()) {
            return Arrays.asList(createTableSql);
        }

        TableDescription td = new TableDescription();
        td.setSchemaName(schemaName);
        td.setTableCode(tableName);
        td.setTableName(tableRemarks);
        td.setTableType(TableType.PTTABLE);
        List<String> results = db.getTableColumnCommentDefinition(td, fieldNames);
        results.add(0, createTableSql);
        return results;
    }

    private GenerateSqlUtils() {
        throw new IllegalStateException();
    }

}
